<?php
namespace app\index\controller;

use app\common\model\facade\Captcha;
use app\common\model\UserFission;
use app\common\model\UserMain;
use app\common\model\VerifyCode;
use PHPMailer\PHPMailer\PHPMailer;
use think\facade\Cookie;
use think\facade\Request;
use think\facade\Validate;
use think\facade\View;
use think\response\Json;

class Account
{

    public function index()
    {
        return redirect('index/account/login');
    }

    public function register()
    {

        global $_G;
        if (!empty($_G['user'])) {
            return Request::isPost() ? show_error('您已登录，请退出后再操作', 'index/index/index') : redirect('index/index/index');
        }
        if (Request::isPost()) {
            if (!$_G['setting']['allow_register']) {
                return show_error('目前禁止自助注册新用户，请联系管理员');
            }

            $ip = Request::ip();

//            $ipCount = UserMain::where('register_ip', '=', $ip)->count();
//            if ($ipCount >= 1){
//                return show_error('请不要重复注册账号，当前无法注册！！');
//            }

            if ($_G['setting']['email_register']) {
                if (!$email = Request::post('email/s', '')) {
                    return show_error('请输入邮箱地址');
                }
                if (!$verify_code = Request::post('verify_code/s', '')) {
                    return show_error('请输入验证码');
                }

                $verify = VerifyCode::where([['email', '=', $email], ['code', '=', $verify_code], ['status', '=', 1]])->find();
                if (!$verify) {
                    return show_error('验证码错误请重新获取');
                }
                if ($verify->out_time <= Request::time()) {
                    return show_error('验证码已失效');
                }
            }

            if (!$password = Request::post('password/s', '')) {
                return show_error('请输入新密码');
            }
            if ($password !== Request::post('password_confirm/s', '')) {
                return show_error('两次输入密码不相同');
            }
            $post = [
                'username'     => Request::post('username/s', ''),
                'password'     => $password,
                'password_see' => $password,
                'email'        => empty($verify) ? '' : $verify->email,
                'email_verify' => empty($verify) ? 0 : 1,
                'type'         => 'member',
                'discount'     => 10,
                'status'       => $_G['setting']['register_review'] ? 0 : 1,
            ];

            $user = UserMain::create($post);
            if (false !== $user->getError()) {
                return show_error($user->getError());
            }

            $user->login();
            if (!empty($verify)) {
                $verify->status = 0;
                $verify->save();
            }
            if ($spread_uid = authcode(Cookie::get('spread_uid'))) {
                $spread_user = $_G['uid'] != $spread_uid ? UserMain::where('uid', '=', $spread_uid)->find() : false;
                if (!empty($spread_user) && !empty($_G['setting']['user_fission']) && $_G['setting']['user_fission_lv'] >= 0 && !UserFission::where('create_ip', '=', Request::ip())->find()) {
                    $user->up_uid = $spread_uid;
                    $user->save();
                    UserFission::create([
                        'spread_uid'  => $spread_uid,
                        'fission_uid' => $user->uid,
                        'floor'       => 1,
                    ]);
                    Cookie::delete('spread_uid');
                }
            }
            return show_success('账户注册成功！', 'index/index/index');
        }
        return View::config(['layout_on' => false])->fetch();
    }

    public function login()
    {
        global $_G;

        if (isMobile()){
            if (!empty($_G['user'])) {
                return Json::create(['code' => 1, 'error' => '已登录']);
            }

            if (Request::isPost()){
                if (!$account = Request::post('account')) {
                    return Json::create(['code' => 0, 'error' => '请输入账号']);
                }
                if (!$password = Request::post('password')) {
                    return Json::create(['code' => 0, 'error' => '请输入密码']);
                }

                if (Validate::isEmail($account)) {
                    $type = 'email';
                } else if (Validate::isMobile($account)) {
                    $type = 'mobile';
                } else {
                    $type = 'username';
                }

                if (!$user = UserMain::where($type, '=', $account)->find()) {
                    return Json::create(['code' => 0, 'error' => '账号不存在']);
                }
                if ($user['status'] == -2) {
                    return Json::create(['code' => 0, 'error' => '用户已注销']);
                }
                if ($user['status'] == -1) {
                    return Json::create(['code' => 0, 'error' => '账户已被禁用']);
                }
                if (!password_verify(md5($password), $user['password'])) {
                    return Json::create(['code' => 0, 'error' => '密码错误']);
                }
                $user->save();
                $user->login();
                return Json::create(['code' => 1, 'error' => '登录成功']);
            }

        }else{
            if (!empty($_G['user'])) {
                return Request::isPost() ? show_error('您已登录，即将为您跳转', 'index/index/index') : redirect('index/index/index');
            }
            if (Request::isPost()) {
                if (!$account = Request::post('account')) {
                    return show_error('请输入帐户名');
                }
                if (!$password = Request::post('password')) {
                    return show_error('请输入密码');
                }
                if (!Captcha::check(Request::post('verify_code/s'))) {
                    return show_error('验证码输入错误');
                }
                if (Validate::isEmail($account)) {
                    $type = 'email';
                } else if (Validate::isMobile($account)) {
                    $type = 'mobile';
                } else {
                    $type = 'username';
                }
                if (!$user = UserMain::where($type, '=', $account)->find()) {
                    return show_error('账号不存在！');
                }
                if ($user['status'] == -2) {
                    return show_error('用户已注销');
                }
                if ($user['status'] == -1) {
                    return show_error('用户已被禁用');
                }
                if (!password_verify(md5($password), $user['password'])) {
                    return show_error('密码错误！');
                }
                $user->save();
                $user->login();
                return show_success('登录成功！', 'index/index/index', '', -1);
            }
            return View::config(['layout_on' => false])->fetch();
        }


    }

    public function reset_password()
    {
        global $_G;
        if (Request::isPost()) {
            if (empty($_G['setting']['email_reset_password'])) {
                return show_error('抱歉，本站尚未开通自助重置密码功能。');
            }
            if (empty($_G['setting']['email_host']) || empty($_G['setting']['email_port']) || empty($_G['setting']['email_username']) || empty($_G['setting']['email_password'])) {
                return show_error('抱歉，我们暂未开启找回密码功能', url('index/account/login'));
            }
            if (!$email = Request::post('email/s', '')) {
                return show_error('请输入绑定的邮箱地址');
            }
            if (!$verify_code = Request::post('verify_code/s', '')) {
                return show_error('请输入验证码');
            }

            $verify = VerifyCode::where([['email', '=', $email], ['code', '=', $verify_code], ['status', '=', 1]])->find();
            if (!$verify) {
                return show_error('验证码错误请重新获取');
            }
            if ($verify->out_time <= Request::time()) {
                return show_error('验证码已失效');
            }
            if (!$password = Request::post('password/s', '')) {
                return show_error('请输入新密码');
            }
            if ($password !== Request::post('password_confirm/s', '')) {
                return show_error('两次输入密码不相同');
            }
            $user = UserMain::where('email', '=', $verify->email)->find();
            if (!$user) {
                return show_error('账户不存在');
            }
            $user->password     = Request::post('password/s');
            $user->password_see = Request::post('password/s');
            $user->save();
            $user->login();
            $verify->status = 0;
            $verify->save();

            return show_success('密码重置成功', url('index/account/login'));
        }
        return View::config(['layout_on' => false])->fetch();
    }

    public function get_verify_code($email = '', $type = '', $find = null)
    {
        global $_G;
        if (!Request::isAjax() || !Request::isPost()) {
            return show_error('请求类型错误');
        }
        if (!in_array($type, ['register', 'reset'])) {
            return show_error('类型错误');
        }
        if (!Validate::isEmail($email)) {
            return show_error('邮箱输入错误');
        }
        if (empty($_G['setting']['email_host']) || empty($_G['setting']['email_port']) || empty($_G['setting']['email_username']) || empty($_G['setting']['email_password'])) {
            return show_error('本站尚不支持邮箱找回密码');
        }
        if (!empty($find) && !$user = UserMain::where('email', '=', $email)->find()) {
            return show_error('未找到相关账号，请确认邮箱是否输入正确');
        }
        VerifyCode::where('email', '=', $email)->update(['status' => 0]);
        $verify = VerifyCode::create([
            'uid'   => empty($user) ? 0 : $user->uid,
            'email' => $email,
        ]);
        $mail            = new PHPMailer;
        $mail->SMTPDebug = 0;
        $mail->isSMTP();
        $mail->isHTML(true);
        $mail->SMTPSecure = 'ssl';
        $mail->Host       = $_G['setting']['email_host'];
        $mail->Port       = $_G['setting']['email_port'];
        $mail->SMTPAuth   = true;
        $mail->Username   = $_G['setting']['email_username'];
        $mail->Password   = $_G['setting']['email_password'];
        $mail->From       = $_G['setting']['email_username'];
        $mail->FromName   = $_G['setting']['email_fromname'] ?? $_G['setting']['site_name'];
        $mail->addAddress($email);
        $mail->Subject = sprintf('您在%s申请的校验码（系统自动邮件,请勿回复）', $_G['setting']['site_name']);
        $mail->Body    = str_replace(['[REGISTER_CODE]', '[RESET_CODE]'], $verify->code, $_G['setting']['email_' . $type . '_content']);
        $mail->AltBody = str_replace(['[REGISTER_CODE]', '[RESET_CODE]'], $verify->code, $_G['setting']['email_' . $type . '_content']);
        if ($mail->send()) {
            return show_success('验证码发送成功');
        }
        return show_error('验证码获取失败，请稍后再试');

    }

    public function logout()
    {
        (new UserMain)->logout();
        return redirect('index/account/login');
    }
}
